<template>
	<div class="compbody">
		<div class="contenter" :style="pageStyle" :key="Refreshkey">
			<es-drager v-for="item in drawList" :key="item.elkye" v-bind="EsDragerBind(item)">
				<component :is="item.name" v-bind="item.props" ref="drawRef">
					<template v-if="item.text">{{ item.text }}</template>
				</component>
			</es-drager>
		</div>
	</div>
</template>
<script setup>
	import { ref, onMounted, computed } from 'vue';
	import { deepClone, sleep, updatedItems } from '@/utils/index';
	import { pageOptioon } from '@/config/index.js';
	import { storeToRefs } from 'pinia';
	import { pubcss } from '@/css/index.js';
	import useConfigMap from '@/store/config/index.js';
	import { usePrintStore } from '@/store/print/index.js';
	import { getToothColorMap, getRequire, getPrintTemplate, getOrderDetail } from '@/api/PlaceOrder/index';

	// 牙色、设计要求仓库
	const configMap = useConfigMap();
	// 牙色、设计要求
	const { Tcolor, Yrequire } = storeToRefs(configMap);

	//打印配置仓库
	const printStore = usePrintStore();

	// 当前打印机索引
	const { BdPrintItem } = storeToRefs(printStore);

	// 纸张配置
	const pageOpt = ref(deepClone(pageOptioon));
	// 纸张样式
	const pageStyle = computed(() => {
		return {
			width: `${pageOpt.value.width}mm`,
			height: `${pageOpt.value.height}mm`
		};
	});

	// EsDrager插件绑定参数
	const EsDragerBind = computed(() => {
		return (item) => {
			return {
				// 是否打开边框
				border: false,
				// 检测父级元素
				boundary: true,
				// 开启辅助线
				markline: false,
				// 是否可以旋转
				rotatable: item.rotatable,
				// 是否可以缩放
				resizable: item.resizable ?? true,
				// 开启吸附
				snap: true,
				// 吸附阈值
				snapThreshold: 10,
				// 显示的缩放handle列表
				resizeList: [],
				// 是否禁用方向键
				disabledKeyEvent: false,
				left: item.x,
				top: item.y,
				width: item.w,
				height: item.h,
				minWidth: 10,
				minHeight: 16,
				angle: item.rotate ?? 0
			};
		};
	});

	// 刷新key
	const Refreshkey = ref(new Date().getTime());

	const excludedkeys = ['pr-title', 'pr-label2', 'xl-divider'];

	// 组件ref
	const drawRef = ref('');

	// 画板数据
	const drawList = ref([]);

	// 获取配置Map
	const getConfigMap = async () => {
		if (Object.keys(Tcolor.value).length > 0) return;
		const [color, require] = await Promise.all([getToothColorMap(), getRequire()]);
		if (color || require) {
			Tcolor.value = color.data;
			Yrequire.value = require.data;
		}
	};

	// 刷新dom
	const refreshDom = () => (Refreshkey.value = new Date().getTime());

	// 更新组件宽高
	const updateWidth = async () => {
		const exc = ['xl-divider', 'pr-barcode', 'pr-title'];
		return new Promise(async (resolve) => {
			for (var i = 0; i < drawRef.value.length; i++) {
				if (!exc.includes(drawList.value[i].name)) Object.assign(drawList.value[i], { w: drawRef.value[i].$el.offsetWidth, h: drawRef.value[i].$el.offsetHeight });
			}
			resolve();
		});
	};

	// 初始化打印机
	const initPrinter = (index) => {
		let LODOP = getLodop();
		LODOP.PRINT_INIT();
		LODOP.SET_PRINTER_INDEX(index);
		LODOP.SET_SHOW_MODE('HIDE_PAPER_BOARD', 1);
		LODOP.SET_PREVIEW_WINDOW(0, 1, 0, 800, 600, '');
		LODOP.SET_PRINT_MODE('AUTO_CLOSE_PREWINDOW', 1);
		LODOP.SET_SHOW_MODE('LANDSCAPE_DEFROTATED', 1);
		LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true);
		return LODOP;
	};

	// 批量打印确认单
	const batchPrinting = async (template, task = [], type = 'confirmationform') => {
		await sleep(800);
		const LODOP = initPrinter(BdPrintItem.value.value);
		const res = await getPrintTemplate({ patient_print_config_id: Number(template) });
		const content = res?.data?.content_local;
		const result = content ? deepClone(JSON.parse(content)) : null;

		if (result?.pageOpt) pageOpt.value = result.pageOpt;
		if (result?.components.length > 0) {
			drawList.value = result.components;
			LODOP.SET_PRINT_PAGESIZE(result.pageOpt.orientation, `${pageOpt.value.PrintSize.width}mm`, `${pageOpt.value.PrintSize.height}mm`);
			for (const order_id of task) await printTask(order_id, type);
		}
		return new Promise(async (resolve) => {
			LODOP.On_Return = () => resolve(true);
			import.meta.env.VITE_PRINT_MODE == 'dev' ? LODOP.PREVIEW() : LODOP.PRINT();
		});
	};

	// 数据赋值队列
	const printTask = async (ordersn, type) => {
		const detailres = await getOrderDetail(type == 'confirmationform' ? { order_id: ordersn } : { order_sn: ordersn }).catch((err) => ElMessage.error(err));
		if (detailres) {
			if (pageOpt.value.adaptive) refreshDom();
			for (const item of updatedItems(detailres.data, Tcolor, Yrequire)) {
				drawList.value.filter((item) => !excludedkeys.includes(item.name)).forEach((drawItem) => (drawItem.props.text = item[drawItem.key]));
				await sleep(300);
				if (pageOpt.value.adaptive) await updateWidth();
				LODOP.NewPage();
				LODOP.ADD_PRINT_HTM(0, 0, 'RightMargin:0mm', 'BottomMargin:0mm', `<style>${pubcss}</style><body>${document.querySelector('.contenter').innerHTML}</body>`);
			}
		}
	};

	onMounted(async () => {
		await getConfigMap();
	});

	defineExpose({ batchPrinting });
</script>
<style lang="scss" scoped>
	.compbody {
		display: flex;
		justify-content: center;

		.contenter {
			width: 210mm;
			height: 118mm;
			background-color: #fcf7f7;
			pointer-events: fill;
			position: relative;
			overflow: hidden;
		}
	}
</style>
